const TradingStrategy = require('./TradingStrategy');
const Order = require('../core/Order');

/**
 * 随机交易策略
 * 随机决定是否交易及交易方向
 */
class RandomStrategy extends TradingStrategy {
  /**
   * 决策方法
   * @param {MarketEnvironment} market - 市场环境
   * @param {Investor} investor - 投资者
   * @returns {Order|null} 订单或null
   */
  decide(market, investor) {
    // 添加随机性，不是每个时间步都会交易
    if (Math.random() > 0.3) {
      return null;
    }

    // 随机选择一个资产
    const assets = Array.from(market.assets.values());
    if (assets.length === 0) {
      return null;
    }
    
    const asset = assets[Math.floor(Math.random() * assets.length)];
    
    // 随机决定买卖方向
    const isBuy = Math.random() > 0.5;
    
    // 确定交易价格和数量
    const currentPrice = asset.getPrice();
    // 使用投资者的风险属性来确定价格波动范围
    const priceVariationRange = investor.getPriceVariationRange();
    const priceVariation = (Math.random() - 0.5) * priceVariationRange;
    const price = currentPrice * (1 + priceVariation);
    
    // 根据投资者资本确定交易数量
    const maxAffordable = isBuy ? 
      Math.floor(investor.capital / price) : 
      investor.getPosition(asset.id).quantity;
      
    if (maxAffordable <= 0) {
      return null;
    }
    
    // 随机确定交易数量
    const quantity = Math.ceil(Math.random() * Math.min(maxAffordable, 100));
    
    if (quantity <= 0) {
      return null;
    }
    
    return new Order(
      investor.id,
      asset.id,
      isBuy ? 'buy' : 'sell',
      price,
      quantity
    );
  }
}

module.exports = RandomStrategy;